package cn.cloudtogo.common.util;

import cn.cloudtogo.common.GendbException;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author yaolianhua789@gmail.com
 **/
public final class RedisUrlHelper {
    private RedisUrlHelper() {
    }

    public static RedisConnectionInfo parseUrl(String url) {
        try {
            URI uri = new URI(url);
            String scheme = uri.getScheme();
            if (!"redis".equals(scheme) && !"rediss".equals(scheme)) {
                throw new GendbException("invalid redis url [" + url + "]");
            }
            boolean useSsl = ("rediss".equals(scheme));
            String username = null;
            String password = null;
            if (uri.getUserInfo() != null) {
                String candidate = uri.getUserInfo();
                int index = candidate.indexOf(':');
                if (index >= 0) {
                    username = candidate.substring(0, index);
                    password = candidate.substring(index + 1);
                } else {
                    password = candidate;
                }
            }

            RedisConnectionInfo redisConnectionInfo = new RedisConnectionInfo(url, useSsl, username, password, uri.getHost(), uri.getPort());

            return redisConnectionInfo;
        } catch (URISyntaxException ex) {
            throw new GendbException(String.format("parse redis url error. [%s]", ex.getMessage()));
        }
    }

}
